import { contextBridge, ipcRenderer } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'

// Custom APIs for renderer
const api = {}
const storeApi = {
  ipcRenderer: {
    setStoreValue: (key, value) => {
      ipcRenderer.send('store:set', key, value)
    },

    getStoreValue(key) {
      const resp = ipcRenderer.sendSync('store:get', key)
      return resp
    }
  }
}

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI)
    contextBridge.exposeInMainWorld('api', api)
    contextBridge.exposeInMainWorld('storeApi', storeApi)
  } catch (error) {
    console.error(error)
  }
} else {
  window.electron = electronAPI
  window.api = api
  window.storeApi = storeApi
}
